import { defineStore } from 'pinia'

export const useApiDatasetStore = defineStore('apiDataset', {
	state: () => ({
		formData: {
			id: '',
			dataConnectorId: '',
			datasetId: '',
			itemConfig: {
				// API接口路径
				apiPath: '',
				// API请求方法
				apiMethod: 'GET',
				// API请求参数
				apiParams: {},
				// 驼峰转换状态
				enableCamelCase: false,
				// 选中的列
				selectedColumns: [],
				// 格式化配置
				formatConfig: [],
				// 表格列定义
				columns: []
			}
		},
		// 查询结果
		queryResult: [],
		// API接口列表
		apiList: [],
		// 连接器信息
		connectorInfo: null
	}),

	getters: {
		// 获取选中的列名
		selectedColumnNames: (state) => {
			if (!state.formData.itemConfig.selectedColumns || state.formData.itemConfig.selectedColumns.length === 0) {
				return '未选择'
			}
			return state.formData.itemConfig.selectedColumns.join('、')
		},

		// 获取API接口信息
		selectedApiInfo: (state) => {
			if (!state.formData.itemConfig.apiPath || !state.apiList.length) {
				return null
			}
			return state.apiList.find((api) => api.apiPath === state.formData.itemConfig.apiPath)
		},

		// 检查配置是否完整
		isConfigComplete: (state) => {
			const config = state.formData.itemConfig
			return !!(config.apiPath && config.selectedColumns && config.selectedColumns.length > 0)
		}
	},

	actions: {
		// 设置表单数据
		setFormData(data) {
			this.formData = { ...this.formData, ...data }
		},

		// 更新itemConfig
		updateItemConfig(config) {
			this.formData.itemConfig = { ...this.formData.itemConfig, ...config }
		},

		// 设置API接口路径
		setApiPath(apiPath) {
			this.formData.itemConfig.apiPath = apiPath
		},

		// 设置API请求方法
		setApiMethod(apiMethod) {
			this.formData.itemConfig.apiMethod = apiMethod
		},

		// 设置API请求参数
		setApiParams(apiParams) {
			this.formData.itemConfig.apiParams = apiParams
		},

		// 设置选中的列
		setSelectedColumns(columns) {
			this.formData.itemConfig.selectedColumns = columns
		},

		// 设置表格列定义
		setColumns(columns) {
			this.formData.itemConfig.columns = columns
		},

		// 设置格式化配置
		setFormatConfig(formatConfig) {
			this.formData.itemConfig.formatConfig = formatConfig
		},

		// 更新查询结果
		updateQueryResult(result) {
			this.queryResult = result
		},

		// 设置API接口列表
		setApiList(apiList) {
			this.apiList = apiList
		},

		// 设置连接器信息
		setConnectorInfo(connectorInfo) {
			this.connectorInfo = connectorInfo
		},

		// 重置store
		$reset() {
			this.formData = {
				id: '',
				dataConnectorId: '',
				datasetId: '',
				itemConfig: {
					apiPath: '',
					apiMethod: 'GET',
					apiParams: {},
					enableCamelCase: false,
					selectedColumns: [],
					formatConfig: [],
					columns: []
				}
			}
			this.queryResult = []
			this.apiList = []
			this.connectorInfo = null
		}
	}
})
